package com.kol.collect.exception;

import com.kol.collect.common.AjaxJson;
import com.kol.collect.common.util.FastJsonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@RestControllerAdvice

public class RestExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public final AjaxJson<Object> handleAllExceptions(Exception ex, WebRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setMsg(ex.getMessage());
        ajaxJson.setStatus(AjaxJson.STATUS_EXCEPTION);
        return ajaxJson;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public final JSONObject handleAllBusinessExceptions(BusinessException ex) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setMsg(ex.getErrorMessage());
        ajaxJson.setStatus(ex.getErrorCode());
        return JSON.parseObject(FastJsonUtils.toJSONNoFeatures(ajaxJson));
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    public AjaxJson<Object> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
        AjaxJson ajaxJson = new AjaxJson();
        BindingResult bindingResult = ex.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        StringBuffer message = new StringBuffer();
        message.append("[").append(fieldError.getField()).append("=").append(fieldError.getRejectedValue()).append("] ").append(fieldError.getDefaultMessage());
        ajaxJson.setStatus(message.toString());
        ajaxJson.setMsg(AjaxJson.MSG_PARAM_ERROR);
        return ajaxJson;
    }
}
